package com.google.code.p.restrpc.client.proxy;

import java.lang.ref.SoftReference;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author dz
 */
public class RpcProxyMetadataTracker {
    
    private static class RpcProxyMetadataTrackerHolder {
        
        static final RpcProxyMetadataTracker instance = new RpcProxyMetadataTracker();
        
    }
    
    /**
     * 
     * @return
     */
    public static RpcProxyMetadataTracker getInstance() {
        return RpcProxyMetadataTrackerHolder.instance;
    }
    
    private final ConcurrentHashMap<String, SoftReference<RpcProxyMetadata>> rpcRroxyMetadataRefs = new ConcurrentHashMap<String, SoftReference<RpcProxyMetadata>>();
    
    /**
     * 
     * @param rpcProxyMetadata
     */
    void registerRpcProxyMetadata(RpcProxyMetadata rpcProxyMetadata) {
        //clear the gc's entry
        for (Iterator<Entry<String, SoftReference<RpcProxyMetadata>>> iterator = rpcRroxyMetadataRefs.entrySet()
                                                                                                     .iterator(); iterator.hasNext();) {
            Entry<String, SoftReference<RpcProxyMetadata>> entry = iterator.next();
            if (entry.getValue() == null) {
                iterator.remove();
            }
            else if (entry.getValue().get() == null) {
                iterator.remove();
            }
        }
        rpcRroxyMetadataRefs.put(UUID.randomUUID().toString(),
                                 new SoftReference<RpcProxyMetadata>(rpcProxyMetadata));
    }
    
    /**
     * @return
     */
    public Map<String, SoftReference<RpcProxyMetadata>> getRpcProxyMetadatas() {
        return rpcRroxyMetadataRefs;
    }
    
}
